package com.bob.clan.wxconnector.component;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class RestApiComponent {
    private RestTemplate restTemplate = new RestTemplate();

    public String post(String url,Map<String,Object> params) throws JsonProcessingException {
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建请求体
        Map<String, Object> requestBody = new HashMap<>();
        params.forEach((key,value)->{
            requestBody.put(key, value);
        });

        // 将请求体转换为JSON字符串
        HttpEntity<String> requestEntity = new HttpEntity<>(new MappingJackson2HttpMessageConverter().getObjectMapper().writeValueAsString(requestBody), headers);

        // 调用外部API
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        // 返回响应体
        return response.getBody();
    }
}
